<template>
    <div class="content-wrapper" v-loading.fullscreen.lock="fullscreenLoading">
        <el-row class="content-row">
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="140px">
                <el-row>
                    <el-col :span="15">

                        <el-form-item label="商品名称" prop="goodsName">
                            <el-input v-model="addForm.goodsName" maxLength="15"  placeholder="不能超过15个字"  style="width:52%;"></el-input>
                        </el-form-item>

<!--                        <el-form-item label="商品最小售卖单位" prop="minNum">-->
<!--                            <el-input v-model="addForm.minNum" placeholder="商品用于售卖的最小单位，如1个" maxLength="10" style="width:52%;"></el-input>-->
<!--                        </el-form-item>-->

                        <el-form-item label="商品数量数量" prop="goodsSpecNum">
                            <el-input v-model="addForm.goodsSpecNum" placeholder="商品用于售卖的最小数量，如1" maxLength="10" style="width:52%;"></el-input>
                        </el-form-item>
                        <el-form-item label="商品单位" prop="goodsSpecUnit">
                            <el-input v-model="addForm.goodsSpecUnit" placeholder="商品用于售卖的最小单位，如个" maxLength="10" style="width:52%;"></el-input>
                        </el-form-item>

                        <el-form-item label="库存数量" prop="inventoryNum">
                            <el-input v-model="addForm.inventoryNum" placeholder="请填写与商品最少售卖单位一致的总数" maxLength="30" style="width:52%;"></el-input>
                        </el-form-item>

                        <el-form-item label="消耗积分" prop="integralNum">
                            <el-input v-model="addForm.integralNum" placeholder="兑换该商品需要的积分" maxLength="30" style="width:52%;"></el-input>
                        </el-form-item>

                        <el-form-item label="市面价格" prop="marketPrice">
                            <el-input v-model="addForm.marketPrice" placeholder="商品市面价值,如 12.99" maxLength="30" style="width:52%;"></el-input>
                        </el-form-item>

                        <el-form-item label="客服电话" prop="serviceTel">
                            <el-input v-model="addForm.serviceTel" placeholder="商品的客服电话，用于客户追踪商品发货情况" maxLength="30" style="width:52%;"></el-input>
                        </el-form-item>
                        <el-form-item label="商品头图" prop="headImg">
                            <el-upload
                                    :action="uploadUrl"
                                    list-type="picture-card"
                                    :class="{disabled:uploadImgNum==1}"
                                    :limit="limit"
                                    :file-list="picList"
                                    :on-preview="handlePictureCardPreviewImg"
                                    :on-success="successUploadImg"
                                    :before-upload="beforeUpload"
                                    :on-remove="handleRemoveImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
                                <img width="100%" :src="dialogImageUrlImg" alt="">
                            </el-dialog>
                            <span>推荐使用1：1的图片，不超过500K</span>
                        </el-form-item>

                        <el-form-item label="商品页轮播图" prop="carouselImg">
                            <el-upload
                                    :action="uploadUrl"
                                    list-type="picture-card"
                                    :class="{disabled:uploadAdvertiseImgNum==5}"
                                    :limit="advertiseLimit"
                                    :file-list="advertisePicList"
                                    :on-preview="handlePictureCardPreviewImg"
                                    :on-success="successUploadAdvertiseImg"
                                    :before-upload="beforeUpload"
                                    :on-remove="handleRemoveAdvertiseImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
                                <img width="100%" :src="dialogImageUrlImg" alt="">
                            </el-dialog>
                            <span>请上传小于200KB，宽高：690*288像素</span>

                        </el-form-item>
                        <el-form-item label="商品页详情图" prop="detailsImg">
                            <el-upload
                                    :action="uploadUrl"
                                    list-type="picture-card"
                                    :class="{disabled:uploadDetailImgNum==5}"
                                    :limit="detailPicLimit"
                                    :file-list="detailPicList"
                                    :on-preview="handlePictureCardPreviewImg"
                                    :on-success="successUploadDetailImg"
                                    :before-upload="beforeUpload"
                                    :on-remove="handleRemoveDetailImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisibleImg" size="tiny">
                                <img width="100%" :src="dialogImageUrlImg" alt="">
                            </el-dialog>
                            <span>请上传小于200KB，宽高：692*288像素</span>

                        </el-form-item>





                        <el-form-item label="兑换说明" prop="activityIntroduce">
                            <el-input type="textarea"   show-word-limit
                                      placeholder="商品市面价值"
                                      maxLength="1000" rows="6" v-model="addForm.description"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


            </el-form>
        </el-row>

        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeTab">取 消</el-button>
            <el-button type="primary" @click="saveForm('addForm',0)">保存</el-button>
            <el-button type="primary" @click="saveForm('addForm',1)">发布</el-button>
        </div>

<!--        <subBannerDeatil v-if='openDialog' v-on:handleclose='subBannerDone' v-bind:editData='editRow' v-bind:index='editIndex'/>-->
    </div>
</template>

<script>

// import CityTree from './CityTree'
// import titleTip from '../../../common/titleTip.vue'
import { add } from '../../../../api/mall/goodsDetail'



export default {
    name: 'goodsDetailAdd',

    data() {
        var checkActivityTime = (rule,value,callback) =>{
            let applyTime = this.addForm.applyTime;
            let activityTime = value;

            if(applyTime.length >  0 && activityTime.length > 0){

                let activityBeginTime = activityTime[0].getTime();
                let activityEndTime = activityTime[1].getTime();

                let applyBeginTime = applyTime[0].getTime();
                let applyEndTime = applyTime[1].getTime();

                console.log(activityBeginTime,activityEndTime,applyBeginTime,applyEndTime)

                if(activityEndTime < applyEndTime){
                    return callback(new Error("活动结束时间不得早于报名结束时间"));
                }else if(activityBeginTime < applyBeginTime){
                    return callback(new Error("报名开始时间不得迟于活动开始时间"));
                }else{
                    callback();
                }
            }else{
                callback();
            }

        };
        var checkApplyTime = (rule,value,callback) =>{
            let applyTime = value;
            let activityTime = this.addForm.time ;
            if(applyTime.length >  0 && activityTime.length > 0){

                let activityBeginTime = activityTime[0].getTime();
                let activityEndTime = activityTime[1].getTime();

                let applyBeginTime = applyTime[0].getTime();
                let applyEndTime = applyTime[1].getTime();

                console.log(activityBeginTime,activityEndTime,applyBeginTime,applyEndTime)


                if(activityEndTime < applyEndTime){
                    return callback(new Error("活动结束时间不得早于报名结束时间"));
                }else if(activityBeginTime < applyBeginTime){
                    return callback(new Error("报名开始时间不得迟于活动开始时间"));
                }else{
                    callback();
                }
            }else{
                callback();
            }

        };
        return {
            activityTypeOptions:[{
                value:'1',
                label:'广告图文类'
            },{
                value:'2',
                label:'现场活动类'
            },{
                value:'3',
                label:'线上报名类'
            }],
            isAdvertise:true,//广告图片
            isOnline:false,//线上活动
            isOffline:false,//线下活动

            externalData:[],
            tableData:[],
            picList:[],
            detailPicList:[],
            advertisePicList:[],

            editIndex: '',
            editRow: {},
            spaces:[],
            uploadImgNum:0,
            uploadDetailImgNum:0,
            uploadAdvertiseImgNum:0,

            dialogImageUrlImg: '',
            dialogVisibleImg: false,


            limit:1,
            advertiseLimit:5,
            detailPicLimit:5,

            openDialog:false,
            viewdialog: false,
            fullscreenLoading:false,

            apply:true,

            detailsImg: [],
            carouselImgList:[],
            uploadUrl:'https://lht.ah-zk.com/qjt/fs/file/upload',
            origin:'https://lht.ah-zk.com/qjt/fs/origin',
            imageStyle: [
                // {
                //     code: "1",
                //     name: "单图",
                //     url: require("../../../../assets/img/01.png")
                // }, {
                //     code: "2",
                //     name: "双图",
                //     url: require("../../../../assets/img/02.png")
                // }, {
                //     code: "3",
                //     name: "三图",
                //     url: require("../../../../assets/img/03.png")
                // }, {
                //     code: "4",
                //     name: "四图",
                //     url: require("../../../../assets/img/04.png")
                // }
            ],
            addForm:{
                goodsName:'',
                goodsSpecNum:'',
                goodsSpecUnit:'',
                minNum:'',
                inventoryNum:'',
                integralNum:'',
                marketPrice:'',
                serviceTel:'',
                headImg:'',
                carouselImg:'',
                detailsImg:'',
                description:'',
                goodsSpecNum:'',
                goodsSpecUnit:''

            },
            addRules: {
                goodsName: [
                    {required: true, message: '请输入商品名称', trigger: ['blur', 'change']}
                ],
                goodsSpecNum: [
                    {required: true, message: '请输入规格数量', trigger: ['blur', 'change']}
                ],
                goodsSpecUnit: [
                    {required: true, message: '请输入规格单位', trigger: ['blur', 'change']}
                ],
                goodsSpecNum: [
                    {required: true, message: '请输入规格数量', trigger: ['blur', 'change']}
                ],
                goodsSpecUnit: [
                    {required: true, message: '请输入规格单位', trigger: ['blur', 'change']}
                ],
                inventoryNum: [
                    {required: true, message: '请输入库存数量', trigger: ['blur', 'change']},
                    { pattern: /^[0-9]*$/, message: '请输数字,请勿输入小数点'}
                ],
                integralNum: [
                    {required: true, message: '请输入兑换积分', trigger: ['blur', 'change']},
                    { pattern: /^[0-9]*$/, message: '请输数字,请勿输入小数点'}
                ],
                marketPrice: [
                    {required: true, message: '请输入市面价格', trigger: ['blur', 'change']},
                    { pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/, message: '请输入两位小数的金额'}
                ],
                serviceTel: [
                    {required: true, message: '请输入客服电话', trigger: ['blur', 'change']}
                ],
                headImg: [
                    {required: true, message: '请上传头图', trigger: ['blur', 'change']}
                ],
                carouselImg: [
                    {required: true, message: '请上传轮播图片', trigger: ['blur', 'change']}
                ]
            }
        };
    },
    created() {
        // this.changeStyle();
        // this.getMoreSpace();
    },
    components:{
        // subBannerDeatil,
        //CityTree,
        //titleTip
    },
    methods: {

        onAddExternalRow(){
            let external = {
                name:'',
                type:2,
                placeholder: '',
                required: true
            }
            this.externalData.push(external)
        },
        //关闭tab
        closeTab(){
            this.closeTagByName('activityAdd');
        },
        //跳转到选择项目弹出框
        viewCity(){
            this.viewdialog=true;
        },
        //选择项目后的回调
        viewinf(e){
            this.viewdialog=false;
            this.addForm.cityList = e;
            let cityNames = "";
            if(e.length!=0){
                for(let i=0;i<e.length;i++){
                    if(i!=0){
                        cityNames+=",";
                    }
                    cityNames+=e[i].cityName;
                }
            }
            this.addForm.cityName=cityNames;
            this.addForm.scope = '2';
        },

        //图片上传删除图片
        handleRemoveImg(file, fileList) {
            this.uploadImgNum=0;
            this.addForm.headImg = null;
        },
        //图片放大方法
        handlePictureCardPreviewImg(file) {
            this.dialogImageUrlImg = file.url;
            this.dialogVisibleImg = true;
        },
        //图片上传成功回调
        successUploadImg(response,file,fileList){
            let f = response.files[0];
            this.addForm.headImg = f.fingerprint;
            this.uploadImgNum=1;
        },

        //图片上传删除图片
        handleRemoveDetailImg(file, fileList) {
            var deleteFileName = file.response.files[0].fingerprint;
            for(var i = 0 ; i < this.detailPicList.length;i++){
                var fileName = this.detailPicList[i];
                if(fileName == deleteFileName){
                    this.detailPicList.splice(i,1);
                    break;
                }
            }
            this.uploadDetailImgNum--;
            this.addForm.activityAdvertiseImg = null;
        },
        //图片放大方法
        // handlePictureCardPreviewDetailImg(file) {
        //     this.dialogImageUrlImg = file.url;
        //     this.dialogVisibleImg = true;
        // },
        //图片上传成功回调
        successUploadDetailImg(response,file,fileList){
            let f = response.files[0];
            //this.addForm.activityAdvertiseImg = f.fingerprint;
            // this.detailPicList.push()
            this.detailsImg.push(f.fingerprint);
            this.uploadDetailImgNum++;

        },

        //图片上传成功回调
        successUploadAdvertiseImg(response,file,fileList){
            let f = response.files[0];
            //this.addForm.activityAdvertiseImg = f.fingerprint;
            this.carouselImgList.push(f.fingerprint)
            this.uploadAdvertiseImgNum++;

            console.log(this.carouselImgList);
        },

        //图片上传删除图片
        handleRemoveAdvertiseImg(file, fileList) {
            var deleteFileName = file.response.files[0].fingerprint;
            for(var i = 0 ; i < this.carouselImgList.length;i++){
                var fileName = this.carouselImgList[i];
                if(fileName == deleteFileName){
                    this.carouselImgList.splice(i,1);
                    break;
                }
            }
            this.uploadAdvertiseImgNum--;
            this.addForm.activityAdvertiseImg = null;

            console.log()
        },
        //文件上传时做文件大小判断
        beforeUpload(file){
            const isLt2M = file.size / 1024 / 1024 < 2
            if(!isLt2M) {
                this.$message({
                    message: '上传文件大小不能超过 200KB!',
                    type: 'warning'
                });
            }
            return isLt2M;
        },
        onDelExternalRow(row,index){
            this.externalData.splice(index,1)
        },
        //提交保存
        saveForm(formName, status) {

            this.addForm.carouselImg = this.carouselImgList.join(",")

            this.addForm.detailsImg = this.detailsImg.join(",")

            this.addForm.status  = status;

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading = true;

                    add(this.addForm).then(res => {
                        if (res.code == '0') {
                            this.fullscreenLoading = false;
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                            this.resetForm('addForm');
                            this.closeTagByName('goodsDetailAdd');
                            this.$router.push('/mall/goodsDetail/list');
                        } else {
                            this.fullscreenLoading = false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }else {
                    return false;
                }
            })

        }
    }
};
</script>

<style scoped>

.content-wrapper{
    height:100%;
    overflow-y: scroll;
}

.content-row{
    height: 94%;
    overflow-y: scroll;
}

.imageFloatLeft {
    width: 40%;
    float: left;
    height: 140px;
    margin-right: 2%;
}

.dialog-footer{
    text-align: center;
}
</style>
